package ru.xpparty.painting;

import java.awt.Graphics;

import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.JPanel;

import ru.xpparty.painting.layer.AbstractLayer;
import ru.xpparty.painting.layer.event.DefaultLayerStateUpdatedListener;

public class Linen extends JPanel {

	private static final long serialVersionUID = -3889212301607059255L;

	private SortedSet<AbstractLayer> layers = new TreeSet<AbstractLayer>();

	public Linen() {
		super(true);
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D gr = (Graphics2D) g;
		configureGraphics(gr);
		drawObjects(gr);
	}

	protected void addLayer(AbstractLayer layer) {
		layer.addLayerStateUpdatedListener(new DefaultLayerStateUpdatedListener(this));
		layers.add(layer);
	}

	protected void removeLayer(AbstractLayer layer) {
		layer.removeAllLayerStateUpdatedListeners();
		layers.remove(layer);
	}

	protected void configureGraphics(Graphics2D gr) {
		gr.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);
		gr.setRenderingHint(RenderingHints.KEY_RENDERING,
				RenderingHints.VALUE_RENDER_QUALITY);
	}

	protected void drawObjects(Graphics2D gr) {
		for (AbstractLayer layer : layers) {
			layer.draw(gr);
		}
	}

	/**
	 * @param layers
	 *            the layers to set
	 */
	void setLayers(SortedSet<AbstractLayer> layers) {
		this.layers = layers;
	}

	/**
	 * @return the layers
	 */
	SortedSet<AbstractLayer> getLayers() {
		return layers;
	}

}
